package com.huatai.datadevelop.websocket;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huatai.datadevelop.entity.InterfaceTableConfigEntity;
import com.huatai.datadevelop.service.InterfaceTableConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hecai
 * @description: TODO
 * @date 2023/2/13 14:36
 * @Version 1.0
 */
@Slf4j
@Component
@ServerEndpoint(value = "/webSocket/timing/page/{interfaceName}")
public class TimingWebSocket {

    /**
     * 存放所有在线的客户端
     */
    public static Map<String, Session> clients = new ConcurrentHashMap<>();
    public static Map<String, Session> sendMessageClients = new ConcurrentHashMap<>();

    private static InterfaceTableConfigService interfaceTableConfigService;

    @Autowired
    public void setUserService(InterfaceTableConfigService interfaceTableConfigService){
        TimingWebSocket.interfaceTableConfigService=interfaceTableConfigService;
    }

    private String interfaceName = "";
    public String getInterfaceName(){
        return interfaceName;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("interfaceName")String interfaceName) {
        Integer integer = pageAnd.addNumber();
        clients.put(interfaceName+session.getId(), session);
        log.info("有新连接加入："+ interfaceName +session.getId()+"，当前在线人数为："+integer);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,@PathParam("interfaceName")String interfaceName) {
        Integer integer = pageAnd.decrement();
        clients.remove(interfaceName+session.getId());
        sendMessageClients.remove(interfaceName+session.getId());
        log.info("有一连接关闭："+interfaceName+session.getId()+"，当前在线人数为："+integer);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param
     */
    @OnMessage
    public void onMessage(@PathParam("interfaceName")String interfaceName,String message, Session session) throws IOException {
        log.info("服务端收到客户端"+interfaceName+session.getId()+"的消息:"+message);
        //连接之后从1开始发送数据
        pageAnd.resSet();
        sendMessageClients.put(interfaceName+session.getId(), session);
        this.sendMessage(interfaceName,1,6400);
    }

    @OnError
    public void onError(@PathParam("interfaceName")String interfaceName,Session session, Throwable error) {
        log.error("连接发生错误");
        clients.remove("连接错误，关闭"+interfaceName+session.getId());
        sendMessageClients.remove("连接错误，关闭"+interfaceName+session.getId());
    }

    /**
     * 群发消息
     * @param
     */
    public void sendMessage(String interfaceName,int page,int limit) throws IOException {
        if(sendMessageClients.size()>0){
            HashMap<String, Object> hashMap = new HashMap<>();
            QueryWrapper<InterfaceTableConfigEntity> qw = new QueryWrapper<>();
            qw.eq("interface_name",interfaceName);
            InterfaceTableConfigEntity entity = interfaceTableConfigService.getOne(qw);
            hashMap.put("page",page);
            hashMap.put("limit",limit);
            HashMap<String, Object> hashMapDataListInfo = interfaceTableConfigService.asyncRequestApi(null, entity, hashMap);
            //发送数据给订阅之后的数据
            for (Map.Entry<String, Session> sessionEntry : sendMessageClients.entrySet()) {
                Session toSession = sessionEntry.getValue();
                String keyValue = toSession.getRequestURI().getPath().replace("/ht-datadevelop/webSocket/timing/page/", "");
                if(interfaceName.equalsIgnoreCase(keyValue)){
                    synchronized (toSession){
                        toSession.getBasicRemote().sendText(JSON.toJSONString(hashMapDataListInfo.get("dataList")));
                        log.info("推送消息结束：");
                    }
                }
            }
        }
    }
}
